from flask import current_app,render_template, g,abort, jsonify,request
from info.models import News, Comment, User
from info.utils.response_code import RET
from . import news_blu
from info.utils.commony import user_login_data
from info import db
@news_blu.route("/<int:news_id>")
@user_login_data
def news_detail(news_id):
    user = g.user

    try:
        # 点击排行
        from info import constants
        news_click = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库操作错误")

    try:
        #新闻内容
        content = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR , errmsg="数据库操作错误")
    if not content:
        abort(404)

    is_collection = False
    if user:
        if content in user.collection_news:
            is_collection = True

    is_fans = False
    try:
        # 用户表数据
        users = User.query.get(user.id)
    except Exception as e:
        current_app.logger.error(e)
        # *详情页退出登陆问题 未解决先注释
        # return jsonify(errno=RET.DBERR , errmsg="数据库操作错误")

    if user:
        if user in users.followers:  # models.py 中定义了这个关系
            is_fans = True

    comments= []
    try:
        """评论排序"""
        comments = Comment.query.filter(Comment.news_id == content.id).order_by(Comment.create_time.desc())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库操作错误")

    comments_list = []
    # 评论列表
    for item in comments:
        comments_list.append(item.to_dict())


    user_like_comments = []
    # 点赞列表
    if user:
        for i in user.like_comments:
            user_like_comments.append(i.to_dict())

    # 获取新闻的作者信息
    author = content.user

    data = {
        "news_click": news_click,
        "user_info": user.to_dict() if user else None,
        "content":content.to_dict(),
        "is_collection":is_collection,
        "comments":comments_list,
        'is_fans':is_fans,
        "user_link_comments": user_like_comments,
        "author": author.to_dict()
    }
    return render_template("news/detail.html", data=data)
    # print(news_id.partition(',')[0].partition('=')[2])

@news_blu.route("/news_collect",methods=["POST"])
@user_login_data
def news_collect():
    """收藏/取消收藏"""
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 判断用户是否登陆
    if not user:
        return jsonify(errno=RET.SESSIONERR , errmsg="用户未登录")
    # 获取参数
    data_dict = request.json
    news_id = data_dict.get("news_id")
    action = data_dict.get("action")
    # 判空,判断参数是否正确
    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR   , errmsg="参数错误")

    # 数据库查询
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库操作错误")

    # js提交action判断
    if action !='collect':

        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)


    try:
        """操作提交"""
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作错误2")

    # 返回
    return jsonify(errno=RET.OK, errmsg="操作成功")

@news_blu.route("/news_comment", methods=["POST"])
@user_login_data
def news_comment():
    # 步骤分析：
    # 1、获取登录用户信息
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 2、接收参数
    data_dict = request.json
    news_id = data_dict.get('news_id')
    news_comment = data_dict.get('comment')
    parent_id = data_dict.get("parent_id")
    # 3、判空
    if not all([news_id,news_comment]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 4、查询新闻，并判断是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库操作错误")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="该新闻不存在")
    # 5、初始化一个评论    步骤分析：
    #    1、获取登录用户信息
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = news_comment
    if parent_id:
        """如果是回复评论，则需要添加parent_id"""
        comment.parent_id = parent_id

    # 6、添加到数据库
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存评论数据失败")

        # 7、返回成功的响应
    return jsonify(errno=RET.OK, errmsg="评论成功", data=comment.to_dict())

@news_blu.route("/followed_user", methods=["POST"])
@user_login_data
def followed_user():
    # 步骤分析：
    # 1、获取登录用户信息
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 2/获取参数
    data_dict = request.json
    action = data_dict.get("action")
    user_id = data_dict.get("user_id")
    # 3/判断
    if not all([action,user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("follow",'unfollow'):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        """操作提交"""

        user = User.query.get(user.id)
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="作者不存在")

        # js提交action判断
    if action == 'follow':
        user.followers.append(user)
    else:
        user.followers.remove(user)

    try:
        """操作提交"""
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作错误")

    return jsonify(errno=RET.OK, errmsg="关注成功")

@news_blu.route("/comment_like", methods=["POST"])
@user_login_data
def comment_like():
    # 1、获取登录用户信息
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 2、获取请求参数、判空  （评论id和action）
    data_dict = request.json
    comment_id = data_dict.get("comment_id")
    action = data_dict.get("action")
    if not all([comment_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("add", "remove"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 3、查询评论并且判断评论是否存在
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")
    # 4、根据action的值进行添加和删除(点赞 / 取消点赞成功以后，增加 / 减少评论的点赞数量comment.like_count)
    if action == "add":
        user.like_comments.append(comment)
        # 点赞成功以后，添加评论的点赞数量
        comment.like_count += 1
    else:
        user.like_comments.remove(comment)
        # 点赞取消以后，删减评论的点赞数量
        comment.like_count -= 1

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="操作失败")

    # 5、返回操作成功
    return jsonify(errno=RET.OK, errmsg="操作成功")